/**
 * 
 */
package com.eagle.coders.core.template.handler;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import java.util.Set;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import com.eagle.coders.core.exceptions.RendererException;
import com.eagle.coders.core.exceptions.TemplateException;

/**
 * @author Anees
 *
 */
public class VelocityReader {
	
//	private Template template;
	private VelocityContext context;
	private VelocityEngine ve;
	
	public VelocityReader() {}
	
	/**
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	private Template getTemplateEngine(String path) throws TemplateException{
		
		context = new VelocityContext();
		ve = new VelocityEngine();
		ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); 
		ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
		
		try{
			ve.init();
			return ve.getTemplate(path);
		}catch(Exception e){
			throw new TemplateException();
		}
	}
	
	/**
	 * 
	 * @param injectMap
	 * @throws IOException
	 */
	public String render(final String path, final Map<String, Object> injectMap) throws TemplateException, RendererException {
		
		Template template = getTemplateEngine(path);
		if(null == template)
			throw new RendererException("Template must be initilazed : Do call getTemplate() Method first!");
		
		StringWriter writer = new StringWriter();

		try{

			if(null != injectMap){
				Set<String> keys= injectMap.keySet();
				for(String key: keys){
					context.put(key, injectMap.get(key));
				}
			}
			template.merge(context, writer);
			
			writer.flush();
			writer.close();
			
			return writer.toString();
		}catch(IOException ioe){
			throw new TemplateException();
		}
	}

}
